package com.qida.clm.core.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

/**
 * Created by edgar on 2015/12/22.
 */
public final class AppUtils {

	public final static String _encoding = "?validate-code=cWlkYTIwMTUrKw==";
	private static final String TAG = "AppUtils";
	
	public static PackageInfo getPackageInfo(Context context){
		String packageName = context.getPackageName();
		try {
			return context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
		} catch (PackageManager.NameNotFoundException e) {
			Log.i(TAG,"Not find package is "+packageName+":"+e.getMessage());
			return null;
		}
	}

	public static int getAppCurrentVersionCode(Context context){
		PackageInfo packageInfo = getPackageInfo(context);
		if(packageInfo != null){
			return packageInfo.versionCode;
		}
		return 0;
	}

	public static Bundle getManifestMeta(Context context){
		try {
			ApplicationInfo ai = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
			return ai.metaData;
		} catch (PackageManager.NameNotFoundException e) {
			Log.e(TAG,"Not find app.");
			return null;
		}
	}

	public static String getManifestMetaValue(Context context,String key){
		Bundle meta = getManifestMeta(context);
		return meta != null ? meta.getString(key) : "";
	}

	public static String getAppCurrentVersionName(Context context){
		PackageInfo packageInfo = getPackageInfo(context);
		if(packageInfo != null){
			return packageInfo.versionName;
		}
		return "";
	}

	public static void installApk(Context context,String filePath){
		if(TextUtils.isEmpty(filePath)){
			return;
		}
		installApk(context,new File(filePath));
	}

	public static void installApk(Context context,File filePath){
		if(!filePath.exists()){
			return;
		}
		Intent intent = new Intent();
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(filePath),
				"application/vnd.android.package-archive");
		context.startActivity(intent);
	}

	public static boolean checkPhone(String phoneNum) {
		Pattern pattern = Pattern.compile("1\\d{2,11}");
		Matcher matcher = pattern.matcher(phoneNum);
		return matcher.matches();
	}
}